package dao;

import demo523.SqlConnection;
import wlw.Users;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


//操作数据：一个功能一个方法一条SQL语句
public class UserDao {
    //1
    public  int addUser(String username,String password) throws SQLException, ClassNotFoundException {

        Connection  connection= SqlConnection.getCon();
        String sql="insert into users(username,password) values(?,?)";
        PreparedStatement  preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        return preparedStatement.executeUpdate();
    }

    //2
    public Users login(String username, String password) throws SQLException, ClassNotFoundException {
         Users users=null;
         int i=1;
         Connection connection=SqlConnection.getCon();
        String sql="select * from users where username=? and password=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        ResultSet  resultSet=preparedStatement.executeQuery();
        if(resultSet.next()){
            users=new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }

        return users;
    }
       //3删除
       public int  deleteUsers(int id) throws SQLException, ClassNotFoundException {
           Connection connection=SqlConnection.getCon();
           String sql="delete from users where id=?";
           PreparedStatement preparedStatement=connection.prepareStatement(sql);
           preparedStatement.setInt(1,id);
           return preparedStatement.executeUpdate();
         }

//4修改
        public int updateUsers(int id,String username,String password) throws SQLException, ClassNotFoundException {
            Connection connection=SqlConnection.getCon();
            String sql="update users set username=?,password=? where id=?";
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.setInt(3,id);
            return preparedStatement.executeUpdate();
        }



}
